package com.zide.system.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.zide.common.core.domain.PageResult;
import com.zide.common.core.domain.entity.SysDept;
import com.zide.common.utils.SecurityUtils;
import com.zide.system.domain.user.vo.result.SystemUserResultVO;
import com.zide.system.domain.user.vo.save.SystemUserSaveVO;
import com.zide.framework.web.mapper.SysUserSearchVO;
import jakarta.validation.Validator;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.zide.common.constant.UserConstants;
import com.zide.common.core.domain.entity.SysRole;
import com.zide.common.core.domain.entity.SysUser;
import com.zide.common.exception.ServiceException;
import com.zide.common.utils.StringUtils;
import com.zide.common.utils.bean.BeanValidators;
import com.zide.common.utils.spring.SpringUtils;
import com.zide.system.domain.post.SysPost;
import com.zide.system.domain.post.SysUserPost;
import com.zide.framework.web.domain.po.SysUserRole;
import com.zide.system.mapper.SysPostMapper;
import com.zide.framework.web.mapper.SysRoleMapper;
import com.zide.framework.web.mapper.SysUserMapper;
import com.zide.system.mapper.SysUserPostMapper;
import com.zide.framework.web.mapper.SysUserRoleMapper;
import com.zide.system.service.ISysConfigService;
import com.zide.system.service.ISysUserService;

/**
 * 用户 业务层处理
 *
 * @author zide
 */
@Service
public class SysUserServiceImpl implements ISysUserService {
    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private SysRoleMapper roleMapper;

    @Autowired
    private SysPostMapper postMapper;

    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Autowired
    private SysUserPostMapper userPostMapper;

    @Autowired
    private ISysConfigService configService;

    @Autowired
    protected Validator validator;

    /**
     * 根据条件分页查询用户列表
     * @return 用户信息集合信息
     */
    @Override
    public PageResult<SystemUserResultVO> selectUserList(SysUserSearchVO searchVO) {
        MPJLambdaWrapper<SysUser> wrapper = new MPJLambdaWrapper<>();
        wrapper.select(SysUser::getUserId,SysUser::getDeptId,SysUser::getUsername,SysUser::getNickname,SysUser::getEmail,
                        SysUser::getMobile,SysUser::getSex,SysUser::getStatus,SysUser::getLoginIp,SysUser::getLoginDate,
                        SysUser::getAvatar,SysUser::getCreator,SysUser::getCreateTime,SysUser::getRemark)
                .selectAs(SysDept::getDeptName,"deptName")
                .selectAs(SysDept::getLeader,"leader")
                        .leftJoin(SysDept.class,SysDept::getDeptId,SysUser::getDeptId);
        if(StrUtil.isNotEmpty(searchVO.getMobile())) {
            wrapper.like(SysUser::getMobile, searchVO.getMobile());
        }
        if(StrUtil.isNotEmpty(searchVO.getUsername())) {
            wrapper.like(SysUser::getUsername, searchVO.getUsername());
        }
        if(ObjectUtil.isNotEmpty(searchVO.getUserId())) {
            wrapper.eq(SysUser::getUserId, searchVO.getUserId());
        }
        if(ObjectUtil.isNotEmpty(searchVO.getDeptId())) {
            wrapper.in(SysUser::getDeptId, searchVO.getDeptId());
        }
        if(ObjectUtil.isNotEmpty(searchVO.getStatus())) {
            wrapper.eq(SysUser::getStatus, searchVO.getStatus());
        }
        return userMapper.selectJoinPage(searchVO, SystemUserResultVO.class,wrapper);
    }

    /**
     * 根据条件分页查询已分配用户角色列表
     * @return 用户信息集合信息
     */
    @Override
    public PageResult<SystemUserResultVO> selectAllocatedList(SysUserSearchVO searchVO) {
        MPJLambdaWrapper<SysUser> wrapper = new MPJLambdaWrapper<>();

        wrapper.select(SysUser::getUserId,SysUser::getDeptId,SysUser::getUsername,SysUser::getNickname,SysUser::getEmail,SysUser::getMobile,SysUser::getStatus,SysUser::getCreateTime)
                .leftJoin(SysDept.class,SysDept::getDeptId,SysUser::getDeptId)
                .leftJoin(SysUserRole.class,SysUserRole::getUserId,SysUser::getUserId)
                .leftJoin(SysRole.class,SysRole::getRoleId,SysUserRole::getRoleId)
                .eq(SysRole::getRoleId,searchVO.getRoleId());
        if(StrUtil.isNotEmpty(searchVO.getUsername())) {
            wrapper.like(SysUser::getUsername,searchVO.getUsername());
        }
        if(StrUtil.isNotEmpty(searchVO.getMobile())) {
            wrapper.like(SysUser::getMobile,searchVO.getMobile());
        }
        return userMapper.selectJoinPage(searchVO,SystemUserResultVO.class, wrapper);
    }

    /**
     * 根据条件分页查询未分配用户角色列表
     * @return 用户信息集合信息
     * select distinct u.user_id, u.dept_id, u.username, u.nickname, u.email, u.mobile, u.status, u.create_time
     * 	    from sys_user u
     * 			 left join sys_dept d on u.dept_id = d.dept_id
     * 			 left join sys_user_role ur on u.user_id = ur.user_id
     * 			 left join sys_role r on r.role_id = ur.role_id
     * 	    where u.deleted = '0' and (r.role_id != #{roleId} or r.role_id IS NULL)
     * 	    and u.user_id not in (select u.user_id from sys_user u inner join sys_user_role ur on u.user_id = ur.user_id and ur.role_id = #{roleId})
     * 	    <if test="username != null and username != ''">
     * 			AND u.username like concat('%', #{username}, '%')
     * 		</if>
     * 		<if test="mobile != null and mobile != ''">
     * 			AND u.mobile like concat('%', #{mobile}, '%')
     * 		</if>
     */
    @Override
    public PageResult<SystemUserResultVO> selectUnallocatedList(SysUserSearchVO searchVO) {
        Page<SysUser> page = new Page<>();
        page.setSize(searchVO.getPageSize());
        page.setCurrent(searchVO.getPageNum());
        Page<SysUser> sysUsers = userMapper.selectUnallocatedList(page,searchVO);
        PageResult<SystemUserResultVO> resultVO = new PageResult<>();
        List<SysUser> records = sysUsers.getRecords();

        resultVO.setList(BeanUtil.copyToList(records,SystemUserResultVO.class));
        resultVO.setTotal(sysUsers.getTotal());
        return resultVO;
    }

    /**
     * 通过用户名查询用户
     *
     * @param username 用户名
     * @return 用户对象信息
     */
    @Override
    public SysUser selectUserByUserName(String username) {
        return userMapper.selectUserByUserName(username);
    }

    /**
     * 通过用户ID查询用户
     *
     * @param userId 用户ID
     * @return 用户对象信息
     */
    @Override
    public SystemUserResultVO selectUserById(Long userId) {
        SysUser sysUser = userMapper.selectUserById(userId);
        return BeanUtil.copyProperties(sysUser,SystemUserResultVO.class);
    }

    /**
     * 查询用户所属角色组
     *
     * @param username 用户名
     * @return 结果
     */
    @Override
    public String selectUserRoleGroup(String username) {
        List<SysRole> list = roleMapper.selectRolesByUserName(username);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysRole::getRoleName).collect(Collectors.joining(","));
    }

    /**
     * 查询用户所属岗位组
     *
     * @param username 用户名
     * @return 结果
     */
    @Override
    public String selectUserPostGroup(String username) {
        List<SysPost> list = postMapper.selectPostsByUserName(username);
        if (CollectionUtils.isEmpty(list)) {
            return StringUtils.EMPTY;
        }
        return list.stream().map(SysPost::getPostName).collect(Collectors.joining(","));
    }

    /**
     * 校验用户名称是否唯一
     * @return 结果
     */
    @Override
    public boolean checkUserNameUnique(SystemUserSaveVO saveVO) {
        Long userId = StringUtils.isNull(saveVO.getUserId()) ? -1L : saveVO.getUserId();
        SysUser info = userMapper.checkUserNameUnique(saveVO.getUsername());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验手机号码是否唯一
     * @return
     */
    @Override
    public boolean checkPhoneUnique(SystemUserSaveVO saveVO) {
        Long userId = StringUtils.isNull(saveVO.getUserId()) ? -1L : saveVO.getUserId();
        SysUser info = userMapper.checkPhoneUnique(saveVO.getMobile());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验email是否唯一
     * @return
     */
    @Override
    public boolean checkEmailUnique(SystemUserSaveVO saveVO) {
        Long userId = StringUtils.isNull(saveVO.getUserId()) ? -1L : saveVO.getUserId();
        SysUser info = userMapper.checkEmailUnique(saveVO.getEmail());
        if (StringUtils.isNotNull(info) && info.getUserId().longValue() != userId.longValue()) {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    /**
     * 校验用户是否允许操作
     */
    @Override
    public void checkUserAllowed(SystemUserSaveVO saveVO) {
        if (StringUtils.isNotNull(saveVO.getUserId()) && saveVO.isAdmin()) {
            throw new ServiceException("不允许操作超级管理员用户");
        }
    }

    /**
     * 校验用户是否有数据权限
     *
     * @param userId 用户id
     */
    @Override
    public void checkUserDataScope(Long userId) {
        if (!SysUser.isAdmin(SecurityUtils.getUserId())) {
            SysUserSearchVO user = new SysUserSearchVO();
            user.setUserId(userId);
            PageResult<SystemUserResultVO> users = SpringUtils.getAopProxy(this).selectUserList(user);
            if (StringUtils.isEmpty(users.getList())) {
                throw new ServiceException("没有权限访问用户数据！");
            }
        }
    }

    /**
     * 新增保存用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int insertUser(SystemUserSaveVO saveVO) {
        SysUser insertBean = BeanUtil.copyProperties(saveVO, SysUser.class);

        // 新增用户信息
        int rows = userMapper.insertUser(insertBean);
        // 新增用户岗位关联
        saveVO.setUserId(insertBean.getUserId());
        insertUserPost(saveVO);
        // 新增用户与角色管理
        insertUserRole(saveVO);
        return rows;
    }

    /**
     * 注册用户信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public boolean registerUser(SysUser user) {
        return userMapper.insertUser(user) > 0;
    }

    /**
     * 修改保存用户信息
     * @return 结果
     */
    @Override
    @Transactional
    public int updateUser(SystemUserSaveVO saveVO) {
        Long userId = saveVO.getUserId();
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 新增用户与角色管理
        insertUserRole(saveVO);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPostByUserId(userId);
        // 新增用户与岗位管理
        insertUserPost(saveVO);
        SysUser updateBean = BeanUtil.copyProperties(saveVO, SysUser.class);
        log.info("修改===》{}",updateBean);
        return userMapper.updateById(updateBean);
    }

    /**
     * 用户授权角色
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    @Override
    @Transactional
    public void insertUserAuth(Long userId, Long[] roleIds) {
        userRoleMapper.deleteUserRoleByUserId(userId);
        insertUserRole(userId, roleIds);
    }

    /**
     * 修改用户状态
     * @return 结果
     */
    @Override
    public int updateUserStatus(SystemUserSaveVO saveVO) {
        SysUser updateBean = BeanUtil.copyProperties(saveVO, SysUser.class);
        return userMapper.updateById(updateBean);
    }

    /**
     * 修改用户基本信息
     *
     * @param user 用户信息
     * @return 结果
     */
    @Override
    public int updateUserProfile(SysUser user) {
        return userMapper.updateById(user);
    }

    /**
     * 修改用户头像
     *
     * @param username 用户名
     * @param avatar   头像地址
     * @return 结果
     */
    @Override
    public boolean updateUserAvatar(String username, String avatar) {
        return userMapper.updateUserAvatar(username, avatar) > 0;
    }

    /**
     * 重置用户密码
     * @return 结果
     */
    @Override
    public int resetPwd(SystemUserSaveVO saveVO) {
        SysUser updateBean = BeanUtil.copyProperties(saveVO, SysUser.class);
        return userMapper.updateById(updateBean);
    }

    /**
     * 重置用户密码
     *
     * @param username 用户名
     * @param password 密码
     * @return 结果
     */
    @Override
    public int resetUserPwd(String username, String password) {
        return userMapper.resetUserPwd(username, password);
    }

    /**
     * 新增用户角色信息
     */
    public void insertUserRole(SystemUserSaveVO saveVO) {
        this.insertUserRole(saveVO.getUserId(), saveVO.getRoleIds());
    }

    /**
     * 新增用户岗位信息
     */
    public void insertUserPost(SystemUserSaveVO saveVO) {
        Long[] posts = saveVO.getPostIds();
        if (StringUtils.isNotEmpty(posts)) {
            // 新增用户与岗位管理
            List<SysUserPost> list = new ArrayList<SysUserPost>(posts.length);
            for (Long postId : posts) {
                SysUserPost up = new SysUserPost();
                up.setUserId(saveVO.getUserId());
                up.setPostId(postId);
                list.add(up);
            }
            userPostMapper.batchUserPost(list);
        }
    }

    /**
     * 新增用户角色信息
     *
     * @param userId  用户ID
     * @param roleIds 角色组
     */
    public void insertUserRole(Long userId, Long[] roleIds) {
        if (StringUtils.isNotEmpty(roleIds)) {
            // 新增用户与角色管理
            List<SysUserRole> list = new ArrayList<SysUserRole>(roleIds.length);
            for (Long roleId : roleIds) {
                SysUserRole ur = new SysUserRole();
                ur.setUserId(userId);
                ur.setRoleId(roleId);
                list.add(ur);
            }
            userRoleMapper.batchUserRole(list);
        }
    }

    /**
     * 通过用户ID删除用户
     *
     * @param userId 用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserById(Long userId) {
        // 删除用户与角色关联
        userRoleMapper.deleteUserRoleByUserId(userId);
        // 删除用户与岗位表
        userPostMapper.deleteUserPostByUserId(userId);
        return userMapper.deleteUserById(userId);
    }

    /**
     * 批量删除用户信息
     *
     * @param userIds 需要删除的用户ID
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteUserByIds(Long[] userIds) {
        for (Long userId : userIds) {
            SystemUserSaveVO saveVO = new SystemUserSaveVO();
            saveVO.setUserId(userId);
            checkUserAllowed(saveVO);
            checkUserDataScope(userId);
        }
        // 删除用户与角色关联
        userRoleMapper.deleteUserRole(userIds);
        // 删除用户与岗位关联
        userPostMapper.deleteUserPost(userIds);
        return userMapper.deleteUserByIds(userIds);
    }

    /**
     * 导入用户数据
     *
     * @param userList        用户数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName        操作用户
     * @return 结果
     */
    @Override
    public String importUser(List<SysUser> userList, Boolean isUpdateSupport, String operName) {
        if (StringUtils.isNull(userList) || userList.size() == 0) {
            throw new ServiceException("导入用户数据不能为空！");
        }
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        String password = configService.selectConfigByKey("sys.user.initPassword");
        for (SysUser user : userList) {
            try {
                // 验证是否存在这个用户
                SysUser u = userMapper.selectUserByUserName(user.getUsername());
                if (StringUtils.isNull(u)) {
                    BeanValidators.validateWithException(validator, user);
                    user.setPassword(SecurityUtils.encryptPassword(password));
                    userMapper.insertUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUsername() + " 导入成功");
                } else if (isUpdateSupport) {
                    BeanValidators.validateWithException(validator, user);
                    SystemUserSaveVO saveVO = BeanUtil.copyProperties(u, SystemUserSaveVO.class);

                    checkUserAllowed(saveVO);
                    checkUserDataScope(u.getUserId());
                    user.setUserId(u.getUserId());
                    userMapper.updateUser(user);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、账号 " + user.getUsername() + " 更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、账号 " + user.getUsername() + " 已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + user.getUsername() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }
}
